package com.android.dumiaogou.activity;

import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.text.Html;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.dumiaogou.R;
import com.android.dumiaogou.activity.mine.LoginActivity;
import com.android.dumiaogou.activity.mine.NewGuideActivity;
import com.android.dumiaogou.app.BaseActivity;
import com.android.dumiaogou.fragment.detail.Fragment_AuctioningRule;
import com.android.dumiaogou.fragment.group.Fragment_Orderts_History;
import com.android.dumiaogou.fragment.group.Fragment_PastedTurnover;
import com.android.dumiaogou.model.auction.AuctionDetailSendData;
import com.android.dumiaogou.model.auction.AuctionResultData;
import com.android.dumiaogou.model.auction.Auction_DetailRecentlyData;
import com.android.dumiaogou.model.auction.Auction_DetailRecentlySendData;
import com.android.dumiaogou.model.auction.Auction_JoinBackData;
import com.android.dumiaogou.model.auction.Auction_JoinSendData;
import com.android.dumiaogou.model.auction.Auction_OrderDetailData;
import com.android.dumiaogou.model.auction.Auction_OrderDetailDataCallback;
import com.android.dumiaogou.model.auction.Auction_detail;
import com.android.dumiaogou.model.auction.Auction_detail_rule;
import com.android.dumiaogou.model.auction.Auction_detail_ruleCallback;
import com.android.dumiaogou.model.auction.Auction_pastedturnover;
import com.android.dumiaogou.model.detail.Banner;
import com.android.dumiaogou.model.group.MainList;
import com.android.dumiaogou.service.WebSocketService3;
import com.android.dumiaogou.utils.ConstantsUrl;
import com.android.dumiaogou.utils.HttpUtils;
import com.android.dumiaogou.utils.LoginState;
import com.android.dumiaogou.utils.MyLog;
import com.android.dumiaogou.utils.ObjectUtils;
import com.android.dumiaogou.view.CustomViewpager;
import com.android.dumiaogou.view.RY_Scrollview;
import com.android.dumiaogou.view.group.ViewPagerIndicator;
import com.google.gson.Gson;
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;
import com.mcxtzhang.nestlistview.NestFullListView;
import com.mcxtzhang.nestlistview.NestFullListViewAdapter;
import com.mcxtzhang.nestlistview.NestFullViewHolder;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;


public class GoodsDetailActivity extends BaseActivity  {
    @BindView(R.id.bannerpager_fragment)
    ViewPager bannerpager_fragment;
    @BindView(R.id.viewPagerIndicator1)
    ViewPagerIndicator viewPagerIndicator1;
    @BindView(R.id.viewpager)
    CustomViewpager viewpager;
    @BindView(R.id.refreshLayout)
    TwinklingRefreshLayout refreshLayout;
    @BindView(R.id.scollview)
    RY_Scrollview scrollview;
    @BindView(R.id.bid_auction)
    TextView bidauction;
    @BindView(R.id.rightnow_price)
    TextView rightnow_price;
    @BindView(R.id.market_price)
    TextView market_price;
    @BindView(R.id.product_name)
    TextView product_name;
    @BindView(R.id.begin_price)
    TextView begin_price;
    @BindView(R.id.addprice_range)
    TextView addprice_range;
    @BindView(R.id.brokerage)
    TextView brokerage;
    @BindView(R.id.safe_price)
    TextView safe_price;
    @BindView(R.id.top_price)
    TextView top_price;
    @BindView(R.id.ll_safe_price)
    LinearLayout ll_safe_price;
    @BindView(R.id.auctioning_counttime)
    TextView auctioning_counttime;
    @BindView(R.id.reutrns_rate)
    TextView reutrns_rate;
    @BindView(R.id.kill_minute)
    TextView kill_minute;
    @BindView(R.id.kill_second)
    TextView kill_second;
    @BindView(R.id.kill_millsecond)
    TextView kill_millsecond;
    @BindView(R.id.cd_day)
    TextView cd_day;
    @BindView(R.id.cd_hour)
    TextView cd_hour;
    @BindView(R.id.cd_minute)
    TextView cd_minute;
    @BindView(R.id.cd_second)
    TextView cd_second;
    @BindView(R.id.ll_count_down1)
    LinearLayout ll_cd1;
    @BindView(R.id.ll_count_down2)
    LinearLayout ll_cd2;
    @BindView(R.id.bid_range_ll)
    LinearLayout bid_range_ll;
    @BindView(R.id.bid_range)
    LinearLayout bid_range;
    @BindView(R.id.no_bidhistory)
    TextView no_bidhistory;
    @BindView(R.id.bid_history)
    LinearLayout bid_history;
    @BindView(R.id.no_bidrange)
    TextView no_bidrange;
    @BindView(R.id.detail_grid_sort_range)
    NestFullListView detail_grid_sort_range;
    @BindView(R.id.detail_grid_sort)
    NestFullListView detail_grid_sort;
    @BindView(R.id.have_consumered_money)
    TextView have_consumered_money;
    @BindView(R.id.detail_goods_ll)
    LinearLayout detail_goods_ll;
    @BindView(R.id.shareing_order_lt)
    RelativeLayout shareing_order_lt;
    @BindView(R.id.past_turnover_lt)
    RelativeLayout past_turnover_lt;
    @BindView(R.id.auction_rule_lt)
    RelativeLayout auction_rule_lt;
    @BindView(R.id.shareing_order_v)
    View shareing_order_v;
    @BindView(R.id.past_turnover_v)
    View past_turnover_v;
    @BindView(R.id.auction_rule_v)
    View auction_rule_v;
    private FragmentActivity mcontext;
    private GroupFragmentPagerAdapters pagerAdapter;
    private ArrayList<String> Banner = new ArrayList<>();
    private boolean networkConnected;
    private boolean isRunning = true;
    private TextView history_trending_chart;
    private ArrayList<Banner.Bannerdata> Bannerlist = new ArrayList<>();
    private ArrayList<MainList.MainListdata.Mainlistdata> listdata;
    private ArrayList<Auction_DetailRecentlyData.ListBean> bh_listdata = new ArrayList<>();
    private ArrayList<Auction_JoinBackData.SortBean> br_listdata  = new ArrayList<>();
    private LinearLayoutManager mLayoutManager = new LinearLayoutManager(mcontext);
    private AuctionDetailSendData auctionDetailSendData = new AuctionDetailSendData();
    private Auction_JoinSendData auction_joinSendData = new Auction_JoinSendData();
    private int mid;
    private String token;
    private Auction_DetailRecentlySendData recentlySendData = new Auction_DetailRecentlySendData();
    private Auction_DetailRecentlyData recentlyData = new Auction_DetailRecentlyData();
    private Auction_JoinBackData auction_joinBackData = new Auction_JoinBackData();
    private AuctionResultData auctionResultData = new AuctionResultData();
    private Auction_detail auction_detail = new Auction_detail();
    private String auction_id;
    private int currenttime;
    private int currentstart;
    private boolean isstart;
    private boolean isMost;
    private Gson gson = new Gson();
    private String gsonstring = "";
    private String id;
    private WebSocketService3 service;
    private BroadcastReceiver mBroadcastReceiver;
    private Message message;
    private Handler mHandler, mHandler1, mHandler2;
    private boolean isshareing_order = true;
    private boolean ispast_turnover;
    private boolean isauction_rule;
    private String rule;
    AlertDialog dialog;
    private int count = 0;
    private float summary_price = 0;
    private int time;
    private int start;
    private String minute;
    private String second;
    private String millsecond;
    private String order_sn;
    private int  sortlength;
    private int DETAIL_SHOW;
    private String top_fee;
    private boolean isEnd = false;
    private long startTimeMillis = 0L;
    private long endTimeMillis = 0L;
    private String strStartTime;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_detail_goods);
        mcontext = GoodsDetailActivity.this;
        ButterKnife.bind(this);
        networkConnected = ObjectUtils.isNetworkConnected(mcontext);
        DETAIL_SHOW = getIntent().getIntExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TO_DETAIL_SHOW,0);
        if(!LoginState.getInstance().getid(mcontext).equals("")&&LoginState.getInstance().getid(mcontext)!=null) {
            mid = Integer.parseInt(LoginState.getInstance().getid(mcontext));
            token = LoginState.getInstance().getUserInfo(mcontext,2);
        }
        init();
        initData();
    }
    public void setHandler(Handler handler) {
        mHandler = handler;
    }
    public void setHandler1(Handler handler) {
        mHandler1 = handler;
    }
    public void setHandler2(Handler handler) {
        mHandler2 = handler;
    }
    public  void notifyFinish()
    {
        refreshLayout.finishLoadmore();
    }

    //更新商品时间
    private Runnable mRunnable1 = new Runnable(){

        @Override
        public void run() {
            if( currenttime>=0 && !isEnd) {

                long currentTimeMillis = System.currentTimeMillis();
                long intervalStart = startTimeMillis - currentTimeMillis;
                if (intervalStart > 0) {
                    currentstart = (int) intervalStart;
                }else {
                    currentstart = 0;
                }
                auction_detail.getAuction().setStart(currentstart);

                long intervalEnd = endTimeMillis - currentTimeMillis;
                if (intervalEnd > 0) {
                    currenttime = (int) intervalEnd;
                }else {
                    currenttime = 0;
                }
                auction_detail.getAuction().setTime(currenttime);
                if (null == message) {
                    message = new Message();
                } else {
                    message = Message.obtain();
                }
                message.what = 0;
                //发送信息给handler
                handler1.sendMessage(message);
                //每40豪秒重启一下线程
                handler1.postDelayed(mRunnable1, 40);
            }
        }
    };
    private Handler handler1 = new Handler() {
        @Override
        public void handleMessage(Message msg) {

            switch (msg.what) {
                case  0:
                    notifyTimeData();
                    break;
                case 1:

                    break;
                case 2:

                    if(recentlyData.getList().get(0).getMid().equals(mid+""))
                    {
                        isMost=true;
                    }else {
                        isMost = false;
                    }
                        bh_listdata.clear();
                        if (recentlyData.getList() != null && recentlyData.getList().size() > 0) {
                            for (int i = 0; i < recentlyData.getList().size(); i++) {
                                Auction_DetailRecentlyData.ListBean listBean = recentlyData.getList().get(i);
                                String price = listBean.getPrice();
                                price = ObjectUtils.decimalFormat(price);
                                if (i == 0) {

                                    bh_listdata.add(new Auction_DetailRecentlyData.ListBean(Auction_pastedturnover.ListBean.THREE, "抢先"
                                            , listBean.getMid(), listBean.getUsername(), listBean.getPhoto()
                                            , listBean.getType(), listBean.getIp(), listBean.getCity(), listBean.getC_time()
                                            , price));
                                } else
                                {

                                    bh_listdata.add(new Auction_DetailRecentlyData.ListBean(Auction_pastedturnover.ListBean.THREE, "没抢到"
                                            , listBean.getMid(), listBean.getUsername(), listBean.getPhoto()
                                            , listBean.getType(), listBean.getIp(), listBean.getCity(), listBean.getC_time()
                                            , price));
                                }
                            }
                            if(recentlyData.getList().size()<3)
                            {
                                for (int i = recentlyData.getList().size(); i < 3; i++) {

                                    bh_listdata.add(new Auction_DetailRecentlyData.ListBean(Auction_pastedturnover.ListBean.THREE, "没抢到"
                                       ,"","","","","","","",""));
                                }
                            }
                            detail_grid_sort.updateUI();
                            no_bidhistory.setVisibility(View.INVISIBLE);
                            detail_grid_sort.setVisibility(View.VISIBLE);
                        }
                        else
                        {
                            no_bidhistory.setVisibility(View.VISIBLE);
                            detail_grid_sort.setVisibility(View.INVISIBLE);
                        }
//                    bidauction.setText("你已最高");
//                    bidauction.setEnabled(false);
//                    bidauction.setBackgroundResource(R.drawable.corner_gray_bg);
//                    if(recentlyData.getList().size()>0) {
//                        ObjectUtils.photo2(mcontext, recentlyData.getList().get(0).getPhoto(), toastpic_consumer_bid);
//                        detail_phonenumber.setText(recentlyData.getList().get(0).getUsername());
//                        ip_address.setText(recentlyData.getList().get(0).getIp());
//                        recently_auctionprice.setText("￥" + recentlyData.getList().get(0).getPrice());
//                    }
                    break;
                case 3:
                    br_listdata.clear();
                    if (sortlength> 0) {
                        for (int i = 0; i < sortlength; i++) {
                                br_listdata.add(new Auction_JoinBackData.SortBean(Auction_pastedturnover.ListBean.THREE
                                        ,auction_joinBackData.getSort().get(i).getMid(),auction_joinBackData.getSort().get(i).getPhoto()
                                        ,auction_joinBackData.getSort().get(i).getUsername(),auction_joinBackData.getSort().get(i).getCount()));

                        }
                        detail_grid_sort_range.updateUI();
                        no_bidrange.setVisibility(View.INVISIBLE);
                        detail_grid_sort_range.setVisibility(View.VISIBLE);
                    }
                    else
                    {
                        no_bidrange.setVisibility(View.VISIBLE);
                        detail_grid_sort_range.setVisibility(View.INVISIBLE);
                    }
                    break;
            }
        }
    };
    private void init() {
//        history_trending_chart.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                Intent trend_chart = new Intent(mcontext,BaseObject.class);
//                trend_chart.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_OBJEXT_SORT_TITLE,"历史成交走势图");
//                startActivity(trend_chart);
//            }
//        });
        if(DETAIL_SHOW==2) {
            bidauction.setText("立即参与");
            bidauction.setBackgroundResource(R.drawable.corner_red_bg_selector);
        }
        detail_grid_sort_range.setAdapter(new NestFullListViewAdapter<Auction_JoinBackData.SortBean>(R.layout.item_detail_br_grid,br_listdata ) {
            @Override
            public void onBind(int position, Auction_JoinBackData.SortBean testBean, NestFullViewHolder holder) {

                    holder.setVisible(R.id.item_grid_detail_like_ll,false);
                    holder.setVisible(R.id.item_grid_detail_like_ll1,true);
                    ObjectUtils.photoCircle(mcontext,testBean.getPhoto(),(ImageView)holder.getView(R.id.item_detail_bidhistoryimg1));
                    if(position==0)
                    holder.setText(R.id.username, testBean.getUsername());
                    holder.setText(R.id.count, "出价次数:"+testBean.getCount());
            }
        });
        detail_grid_sort.setAdapter(new NestFullListViewAdapter<Auction_DetailRecentlyData.ListBean>(R.layout.item_detail_bh_grid,bh_listdata ) {
            @Override
            public void onBind(int position, Auction_DetailRecentlyData.ListBean testBean, NestFullViewHolder holder) {
                if (testBean.getUsername().equals("") || testBean.getUsername() == null) {
                    holder.setVisible(R.id.item_grid_detail_like_ll, true);
                    holder.setVisible(R.id.item_grid_detail_like_ll1, false);
                } else {
                    holder.setVisible(R.id.item_grid_detail_like_ll, false);
                    holder.setVisible(R.id.item_grid_detail_like_ll1, true);
                    holder.setText(R.id.getting_tv, testBean.getGetting());
                    ObjectUtils.photoCircle(mcontext, testBean.getPhoto(), (ImageView) holder.getView(R.id.item_detail_bidhistoryimg1));
                    if (position == 0) {
                        holder.setBackgroundRes(R.id.getting_ll, R.drawable.corner_red_bg2);
                    } else {
                        holder.setBackgroundRes(R.id.getting_ll, R.drawable.corner_gray_bg2);
                    }
                    holder.setText(R.id.username, testBean.getUsername());
                    holder.setText(R.id.city, testBean.getCity());
                    int time = Integer.parseInt(testBean.getC_time());
                    long msl = (long) time * 1000;
                    SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
                    String text = format.format(msl);
                    holder.setText(R.id.time, text);
                    holder.setText(R.id.money, "¥" + testBean.getPrice());
                }

            }
        });

        viewpager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                viewpager.resetHeight(position);
                switch (position) {
                    case 0:
                        isshareing_order = true;
                        ispast_turnover = false;
                        isauction_rule = false;
                        shareing_order_v.setVisibility(View.VISIBLE);
                        past_turnover_v.setVisibility(View.INVISIBLE);
                        auction_rule_v.setVisibility(View.INVISIBLE);
                        break;
                    case 1:
                        isshareing_order = false;
                        ispast_turnover = true;
                        isauction_rule = false;
                        shareing_order_v.setVisibility(View.INVISIBLE);
                        past_turnover_v.setVisibility(View.VISIBLE);
                        auction_rule_v.setVisibility(View.INVISIBLE);
                        break;
                    case 2:
                        isshareing_order = false;
                        ispast_turnover = false;
                        isauction_rule = true;
                        shareing_order_v.setVisibility(View.INVISIBLE);
                        past_turnover_v.setVisibility(View.INVISIBLE);
                        auction_rule_v.setVisibility(View.VISIBLE);
                        break;
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        viewpager.resetHeight(0);
        scrollview.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
        if(DETAIL_SHOW!=2) {
            refreshLayout.setEnableRefresh(false);
            refreshLayout.setOnRefreshListener(new RefreshListenerAdapter() {
                @Override
                public void onRefresh(final TwinklingRefreshLayout refreshLayout) {
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            refreshLayout.finishRefreshing();
                        }
                    }, 1000);
                }

                @Override
                public void onLoadMore(final TwinklingRefreshLayout refreshLayout) {
                    if (isshareing_order) {
                        Message msg = new Message();
                        msg.what = 1;
                        mHandler.sendMessage(msg);
                    } else if (ispast_turnover) {
                        Message msg = new Message();
                        msg.what = 2;
                        mHandler1.sendMessage(msg);
                    } else {
                        Message msg = new Message();
                        msg.what = 3;
                        mHandler2.sendMessage(msg);
                    }
                }
            });
        }
    }

    private void initData() {
        id = getIntent().getStringExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TO_DETAIL_ID);
        if (DETAIL_SHOW == 2) {
            service = WebSocketService3.getInstance();
            mBroadcastReceiver = new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {
                    String action = intent.getAction();
                    //趣买最新出价消息
                    if (action.equals(WebSocketService3.ACTION_JOINLOG)) {
                        recentlyData = (Auction_DetailRecentlyData) intent.getBundleExtra("bundle5").getSerializable("AuctionJoinLog");
                        if (recentlyData.getList() != null && recentlyData.getList().size() > 0) {
                            Message message = new Message();
                            message.what = 2;
                            handler1.sendMessage(message);
                        }
                    }
                }
            };
            IntentFilter myIntentFilter = new IntentFilter();
            myIntentFilter.addAction(WebSocketService3.ACTION_JOINLOG);
            //注册广播
            mcontext.registerReceiver(mBroadcastReceiver, myIntentFilter);
            GetOrder_Detail();
        } else {
            broadcastReceive();
            auctionDetailSendData.setType("get_auction");
            if(id!=null) {
                auctionDetailSendData.setId(Integer.parseInt(id));
                if(mid!=0){
                    auctionDetailSendData.setMid(mid);
                }
                gsonstring = gson.toJson(auctionDetailSendData);
                service.sendMsg(gsonstring);
            }
            else
            {
                return;
            }
        }

        shareing_order_lt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                isshareing_order = true;
                ispast_turnover = false;
                isauction_rule = false;
                shareing_order_v.setVisibility(View.VISIBLE);
                past_turnover_v.setVisibility(View.INVISIBLE);
                auction_rule_v.setVisibility(View.INVISIBLE);
                viewpager.setCurrentItem(0);
            }
        });
        past_turnover_lt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                isshareing_order = false;
                ispast_turnover = true;
                isauction_rule = false;
                shareing_order_v.setVisibility(View.INVISIBLE);
                past_turnover_v.setVisibility(View.VISIBLE);
                auction_rule_v.setVisibility(View.INVISIBLE);
                viewpager.setCurrentItem(1);
            }
        });
        auction_rule_lt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                isshareing_order = false;
                ispast_turnover = false;
                isauction_rule = true;
                shareing_order_v.setVisibility(View.INVISIBLE);
                past_turnover_v.setVisibility(View.INVISIBLE);
                auction_rule_v.setVisibility(View.VISIBLE);
                viewpager.setCurrentItem(2);
            }
        });
    }

    //获取详情
    private void GetOrder_Detail() {
        networkConnected = ObjectUtils.isNetworkConnected(mcontext);
        String address = ConstantsUrl.domain + ConstantsUrl.ACUTIONORDER_DETAIL;
        MyLog.e("地址", address);
        if (networkConnected) {
            HashMap<String, String> header = ObjectUtils.getHeader(mcontext);
            HashMap<String, String> map = new HashMap<>();
            map.put("order_id", id);
            HttpUtils.get(address, header, map, order_detailCallback);
        } else {
            ObjectUtils.toast(mcontext, "网络连接出现异常");
        }
    }

    Auction_OrderDetailDataCallback order_detailCallback = new Auction_OrderDetailDataCallback() {
        @Override
        public void onError(Call call, Exception e, int id) {
        }

        @Override
        public void onResponse(Auction_OrderDetailData response, int id) {
            if(response.getCode()==0) {
                //详情页初始化
                Auction_OrderDetailData.DataBean data = response.getData();
                String price = data.getPrice();
                price = ObjectUtils.decimalFormat(price);
                rightnow_price.setText("￥" + price);
                String markprice = data.getMarket_price();
                market_price.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
                market_price.setText("￥" + markprice);
                product_name.setText(data.getTitle());
                begin_price.setText("￥" + data.getStart_price());
                addprice_range.setText("￥" + data.getPer_price());
                String appDou = getString(R.string.app_mine_currencyname);
                brokerage.setText(data.getBrokerage()+appDou);
                auctioning_counttime.setText(data.getFirst_countdown()+"秒");
                reutrns_rate.setText(data.getReturns_rate()+" (1个"+appDou+"退"+ data.getReturns_rate()+"个积分)");
                order_sn = data.getOrder_sn();
                auction_id = data.getAuction_id();
                GetBanner1(data.getThumbs());
                pagerAdapter = new GroupFragmentPagerAdapters(getSupportFragmentManager());
                viewpager.setAdapter(pagerAdapter);
                viewpager.setCurrentItem(0);
                recentlySendData.setType("join_log");
                recentlySendData.setOrder_sn(order_sn);
                recentlySendData.setPage(1);
                recentlySendData.setPer_page(3);
                gsonstring = gson.toJson(recentlySendData);
                service.sendMsg(gsonstring);
            }
        }
    };

    //设置广播监听
    private void broadcastReceive() {
        service = WebSocketService3.getInstance();

        mBroadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();
                //更新趣买返回消息
                if (action.equals(WebSocketService3.ACTION_NOT)) {
                    Intent intents = mcontext.getIntent();
                    auctionResultData = (AuctionResultData) intent.getBundleExtra("bundle").getSerializable("AuctionResult");
                    if (auctionResultData != null && auctionResultData.getId().equals(id)) {
                        DealWithResult();
                    }
                }
                //趣买详情信息
                if (action.equals(WebSocketService3.ACTION_DETAIL)) {
                    auction_detail = (Auction_detail) intent.getBundleExtra("bundle4").getSerializable("AuctionGetAuction");
                    //初始化详情界面
                    count = auction_detail.getAuction().getMid_count();
                    have_consumered_money.setText(count+ "");
                    String price = auction_detail.getAuction().getPrice();
                    price = ObjectUtils.decimalFormat(price);
                    rightnow_price.setText("￥" + price);
                    String markprice = auction_detail.getAuction().getMarket_price();
                    market_price.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
                    market_price.setText("￥" + markprice);
                    product_name.setText(auction_detail.getAuction().getTitle());
                    begin_price.setText("￥" + auction_detail.getAuction().getStart_price());
                    addprice_range.setText("￥" +auction_detail.getAuction().getPer_price());
                    String appDou = getString(R.string.app_mine_currencyname);
                    brokerage.setText(auction_detail.getAuction().getBrokerage()+appDou);
                    auctioning_counttime.setText(auction_detail.getAuction().getFirst_countdown()+"秒");
                    reutrns_rate.setText(auction_detail.getAuction().getReturns_rate()+" (1个"+appDou+"退"+auction_detail.getAuction().getReturns_rate()+"个积分)");
                    String safePrice = auction_detail.getAuction().getSafe_price();
                    if(!TextUtils.isEmpty(safePrice) && !safePrice.equals("0")){
                        ll_safe_price.setVisibility(View.VISIBLE);
                        safe_price.setText("￥" + safePrice);
                    }else {
                        ll_safe_price.setVisibility(View.GONE);
                    }
//                    top_price.setText("￥" +auction_detail.getAuction().getTop_price());
                    currenttime = auction_detail.getAuction().getTime()*1000;
                    currentstart = auction_detail.getAuction().getStart()*1000;
                    if(currentstart>0)
                    {
                      isstart = true;
                    }
                    auction_detail.getAuction().setTime(currenttime);
                    auction_detail.getAuction().setStart(currentstart);
                    String active_time = auction_detail.getAuction().getActive_time();
                    strStartTime = ObjectUtils.getStrTime(active_time, "yyyy-MM-dd HH:mm:ss");
                    bidauction.setText(strStartTime + " 开始");
                    startTimeMillis = Long.parseLong(active_time) * 1000 + 2000;
                    endTimeMillis = Long.parseLong(auction_detail.getAuction().getExpire()) * 1000;
                    auction_id = auction_detail.getAuction().getId();
                    handler1.post(mRunnable1);
                    recentlySendData.setType("join_log");
                    String order_sn = auction_detail.getAuction().getId() + "_" + auction_detail.getAuction().getPeriod();
                    recentlySendData.setOrder_sn(order_sn);
                    recentlySendData.setPage(1);
                    recentlySendData.setPer_page(3);
                    gsonstring = gson.toJson(recentlySendData);
                    service.sendMsg(gsonstring);
                    pagerAdapter = new GroupFragmentPagerAdapters(getSupportFragmentManager());
                    viewpager.setAdapter(pagerAdapter);
                    viewpager.setCurrentItem(0);
                    GetBanner();
                    //GetBidHistory();
                }
                //趣买最新出价消息
                if (action.equals(WebSocketService3.ACTION_JOINLOG)) {
                    recentlyData = (Auction_DetailRecentlyData) intent.getBundleExtra("bundle5").getSerializable("AuctionJoinLog");
                    if (recentlyData.getList() != null && recentlyData.getList().size() > 0) {
                        Message message = new Message();
                        message.what = 2;
                        handler1.sendMessage(message);
                    }
                }
                //更新商品竞买时间，价格，出价人
                if (action.equals(WebSocketService3.ACTION_JOINBACK)) {
                    auction_joinBackData = (Auction_JoinBackData) intent.getBundleExtra("bundle3").getSerializable("AuctionJoinBack");
                    String code = auction_joinBackData.getCode();
                    if (code != null && !code.equals("")) {
                        if (Integer.parseInt(code) > 0) {
                            ObjectUtils.toast(mcontext, auction_joinBackData.getMsg());
                        }
                    }
                    //GetBidHistory();
                    //返回数据为此id
                    if(auction_detail.getAuction()!=null)
                    {
                        if (auction_joinBackData.getId() == Integer.parseInt(auction_detail.getAuction().getId()) && !isEnd) {
                            if (auction_joinBackData.getTime() > 0) {
                                long currentTimeMillis = System.currentTimeMillis();
                                currenttime = auction_joinBackData.getTime() * 1000;
                                endTimeMillis = currentTimeMillis + currenttime;
                                auction_detail.getAuction().setTime(currenttime);
                                auction_detail.getAuction().setStart(0);
                            }
                            //返回数据是否为本产品id
//                            count++;
                            summary_price = summary_price + 1;
                          //  have_consumered_money.setText(summary_price+ "");
                            have_consumered_money.setText(count+ "");
                            recentlySendData.setType("join_log");
                            String order_sn = auction_detail.getAuction().getId() + "_" + auction_detail.getAuction().getPeriod();
                            recentlySendData.setOrder_sn(order_sn);
                            recentlySendData.setPage(1);
                            recentlySendData.setPer_page(3);
                            gsonstring = gson.toJson(recentlySendData);
                            service.sendMsg(gsonstring);
                            if (auction_joinBackData.getMid() != mid) {
                                isMost = false;
                                bidauction.setEnabled(true);
                            }else {
                                isMost = true;
                                bidauction.setEnabled(false);
                            }
                            float price = auction_joinBackData.getPrice();
                            if (price > 0) {
                                String appDou = getString(R.string.app_mine_currencyname);
                                bidauction.setText("出价(1"+appDou+"或1赠豆一次)");
//                                bidauction.setEnabled(true);
                                bidauction.setBackgroundResource(R.drawable.corner_red_bg_selector);
                                DecimalFormat decimalFormat=new DecimalFormat("####0.0");
                                String strPrice = decimalFormat.format(price);
                                rightnow_price.setText(strPrice);
                            }
                            if(auction_joinBackData.getSort()!=null)
                            {
                                if(auction_joinBackData.getSort().size()>0)
                                {
                                    if(auction_joinBackData.getSort().size()<3) {
                                        sortlength = auction_joinBackData.getSort().size();
                                    }
                                    else
                                    {
                                        sortlength = 3;
                                    }
                                    Message message = new Message();
                                    message.what = 3;
                                    handler1.sendMessage(message);
                                }
                            }
                        }
                    }
                }
            }
        };
        IntentFilter myIntentFilter = new IntentFilter();
        myIntentFilter.addAction(WebSocketService3.ACTION_NOT);
        myIntentFilter.addAction(WebSocketService3.ACTION_DETAIL);
        myIntentFilter.addAction(WebSocketService3.ACTION_JOINLOG);
        myIntentFilter.addAction(WebSocketService3.ACTION_JOINBACK);
        //注册广播
        mcontext.registerReceiver(mBroadcastReceiver, myIntentFilter);

        }

    @OnClick({R.id.contact_aishang,R.id.bid_history,R.id.safe_price_rule,R.id.detail_goods_ll,R.id.history_trending_ll,R.id.bid_auction,R.id.main_top_back})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.contact_aishang:
                getAgreeMentData();
                break;
            case R.id.bid_history:
                Intent intent_address1 = new Intent(mcontext, BaseObject.class);
                intent_address1.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_OBJEXT_SORT_TITLE, "出价记录");
                if (DETAIL_SHOW == 2) {
                    intent_address1.putExtra("DETAIL_SHOW", 2);
                } else {
                    order_sn = auction_detail.getAuction().getId() + "_" + auction_detail.getAuction().getPeriod();
                }
                intent_address1.putExtra("order_sn", order_sn);
                startActivity(intent_address1);
                break;
            case R.id.safe_price_rule:
                showSafePriceRuleDialog();
                break;
            case R.id.detail_goods_ll:
                Intent intent_address2 = new Intent(mcontext, BaseObject.class);
                intent_address2.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_OBJEXT_SORT_TITLE, "商品详情");
                intent_address2.putExtra("detail_goodsid",id);
                startActivity(intent_address2);
                break;
            case R.id.history_trending_ll:
                Intent intent_q = new Intent(mcontext, NewGuideActivity.class);
                intent_q.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_OBJEXT_SORT_WEB_URL, ConstantsUrl.baseDomain + "home/www/?/#/auction-charts/"+id);
                intent_q.putExtra("title","历史成交走势图");
                startActivity(intent_q);
//                Intent intent_address3 = new Intent(mcontext, BaseObject.class);
//                intent_address3.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_OBJEXT_SORT_TITLE, "历史成交走势图");
//                intent_address3.putExtra("detail_htc","https://jm.lnest.cc/home/www/?/#/auction-charts/"+id);
//                startActivity(intent_address3);
                break;
            case R.id.main_top_back:
//                Intent intent = new Intent();
//                Bundle bundle = new Bundle();
//                bundle.putString("auction_id",auction_detail.getAuction().getId());
//                bundle.putString("auction_period",auction_detail.getAuction().getPeriod());
//                intent.putExtras(bundle);
//                setResult(RESULT_OK, intent);
                finish();
                break;
            case R.id.bid_auction:
                bidauction.setEnabled(false);
                if (LoginState.getInstance().isLogin(mcontext)) {

                    if (bidauction.getText().toString().equals("进入最新一期")) {
                        ObjectUtils.ToDetailActivity(mcontext, 1, id, "");
                        finish();
                    } else if (bidauction.getText().toString().equals("立即参与")) {
                        ObjectUtils.ToDetailActivity(mcontext, 1, auction_id, "");
                        finish();
                    } else {
                        count++;
                        auction_joinSendData.setType("join_auction");
                        auction_joinSendData.setId(Integer.parseInt(id));
                        auction_joinSendData.setMid(mid);
                        auction_joinSendData.setToken(token);
                        gsonstring = gson.toJson(auction_joinSendData);
                        service.sendMsg(gsonstring);
                    }
                } else {
                    startActivity(new Intent(mcontext, LoginActivity.class));
                }
                break;
        }
    }

    private void showSafePriceRuleDialog() {
        LayoutInflater inflater = (LayoutInflater) mcontext
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View v = inflater.inflate(R.layout.dialog_signin_rule, null);
        TextView title = (TextView) v.findViewById(R.id.rule_title);
        TextView sure = (TextView) v.findViewById(R.id.dialog_sure);
        TextView content = (TextView) v.findViewById(R.id.dialog_content);
        title.setText("保底价规则");
        String unit_coin = getString(R.string.app_mine_currencyname);
        String free_coin = getString(R.string.app_mine_zengdou);
        String unit_score = getString(R.string.app_mine_jifen);
        String priceRule = "<div class=\"desc text-left\">\n" +
                "        <p>活动结束时，成交价 低于 保底价，则活动不成立；退还参与者全部"+unit_coin+"和"+free_coin+"。</p>\n" +
                "        <p>退还时，"+free_coin+"只退, 不送"+unit_score+", "+unit_coin+"数 乘以 [保底赠送"+unit_score+"比率] 赠送"+unit_score+"。</p>\n" +
                "        <p>例如：[保底赠送"+unit_score+"比率]为 2，参与者消费 10 "+unit_coin+"和 5 "+free_coin+"，则活动保底时，退还全部"+unit_coin+"和"+free_coin+", 并赠送 20 "+unit_score+"。</p>\n" +
                "    </div>\n" +
                "</div>\n";
        content.setText(Html.fromHtml(priceRule));
        sure.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View view) {
                                        dialog.dismiss();
                                    }
                                }
        );
        dialog = new AlertDialog.Builder(mcontext).setView(v).setCancelable(true).show();
    }

    //获取趣买规则
    private void getAgreeMentData() {
        networkConnected = ObjectUtils.isNetworkConnected(mcontext);
        String address = ConstantsUrl.domain + ConstantsUrl.ACUTIONHOMEBLOCK;
        MyLog.e("地址", address);
        if (networkConnected) {
            HashMap<String, String> header = ObjectUtils.getHeader(mcontext);
            HashMap<String, String> map = new HashMap<>();
            map.put("mark", "agreement");
            HttpUtils.get(address, header, map, dataCallback);
        } else {
            ObjectUtils.toast(mcontext, "网络连接出现异常");
        }
    }

    Auction_detail_ruleCallback dataCallback = new Auction_detail_ruleCallback() {
        @Override
        public void onError(Call call, Exception e, int id) {
        }

        @Override
        public void onResponse(Auction_detail_rule response, int id) {
            if (response.getCode() == 0) {
                rule = response.getData();
                if(!TextUtils.isEmpty(rule)){
                    showRuleDialog();
                }
            }
            else
            {
                ObjectUtils.toast(mcontext, "token过期,无法查看");
            }
        }
    };

    private void showRuleDialog() {
        LayoutInflater inflater = (LayoutInflater) mcontext
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View v = inflater.inflate(R.layout.detail_signin_rule, null);
        TextView title = (TextView) v.findViewById(R.id.rule_title);
        TextView sure = (TextView) v.findViewById(R.id.dialog_sure);
        TextView content = (TextView) v.findViewById(R.id.dialog_content);
        title.setText("用户协议");
        content.setText(Html.fromHtml(rule));
        sure.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View view) {
                                        dialog.dismiss();
                                    }
                                }
        );
        dialog = new AlertDialog.Builder(mcontext).setView(v).setCancelable(true).show();
    }

    /**
     * 处理竞买返回通知消息
     */
    private void DealWithResult() {
        ll_cd1.setVisibility(View.VISIBLE);
        ll_cd2.setVisibility(View.GONE);
        kill_millsecond.setText("00");
        kill_minute.setText("00");
        kill_second.setText("00");
        /**
         * 趣买返回通知重开
         */
        isEnd = true;
        if (auctionResultData.getTime() > 0) {
            /**
             * 更新重开的商品时间
             */
            if (auction_detail != null) {
                bidauction.setText("进入最新一期");
                bidauction.setEnabled(true);
                bidauction.setBackgroundResource(R.drawable.corner_red_bg_selector);
//                    currenttime = auctionResultData.getTime() * 1000;
//                    currentstart =auctionResultData.getStart() * 1000;
//                    auction_detail.getAuction().setTime(auctionResultData.getTime() * 1000);
//                    if(auctionResultData.getStart()>0)
//                    {
//                        isstart = true;
//                    auction_detail.getAuction().setStart(auctionResultData.getStart() * 1000);
//                        }
            } else {
                bidauction.setText(getString(R.string.app_keyname) + "结束");
                bidauction.setEnabled(false);
                bidauction.setBackgroundResource(R.drawable.corner_gray_bg);
            }
        }

    }

    private class GroupFragmentPagerAdapters extends FragmentPagerAdapter {
        public GroupFragmentPagerAdapters(FragmentManager fm) {
            super(fm);
        }


        @Override
        public Fragment getItem(int position) {
            if (position == 2)

            {
                Fragment_AuctioningRule fragment_AuctioningRule = new Fragment_AuctioningRule();
                fragment_AuctioningRule.SecurityInfoFragment(viewpager, position, auction_id);
                return fragment_AuctioningRule;

            } else if (position == 0) {
                Fragment_Orderts_History Orderts_History = new Fragment_Orderts_History();
                Orderts_History.SecurityInfoFragment(viewpager, position, auction_id);
                return Orderts_History;

            } else {
                Fragment_PastedTurnover fragment_bidHistory = new Fragment_PastedTurnover();
                fragment_bidHistory.SecurityInfoFragment(viewpager, position, auction_id);
                return fragment_bidHistory;
            }
        }

        @Override
        public int getCount() {
            return 3;

        }

    }

    /**
     * 获取轮播图
     */
    private void GetBanner() {
        Bannerlist.clear();

        if (auction_detail != null) {
            for (int i = 0; i < auction_detail.getAuction().getThumbs().size(); i++) {
                com.android.dumiaogou.model.detail.Banner.Bannerdata data = new Banner.Bannerdata();
                data.setThumb(auction_detail.getAuction().getThumbs().get(i));
                data.setLink("");
                data.setPath("");
                Bannerlist.add(data);
            }
            //轮播图
            if (Bannerlist != null) {
                viewPagerIndicator1.autoScroll(mcontext.getSupportFragmentManager(), bannerpager_fragment, 1);
                viewPagerIndicator1.setViewPager(Bannerlist);
                viewPagerIndicator1.setNotifyDataSetChanged();
            }
        }
    }

    /**
     * 获取轮播图
     */
    private void GetBanner1(String[] thumbs) {
        Bannerlist.clear();

        for (int i = 0; i < thumbs.length; i++) {
            com.android.dumiaogou.model.detail.Banner.Bannerdata data = new Banner.Bannerdata();
            data.setThumb(thumbs[i]);
            data.setLink("");
            data.setPath("");
            Bannerlist.add(data);
        }
        //轮播图
        if (Bannerlist != null) {
            viewPagerIndicator1.autoScroll(mcontext.getSupportFragmentManager(), bannerpager_fragment, 1);
            viewPagerIndicator1.setViewPager(Bannerlist);
            viewPagerIndicator1.setNotifyDataSetChanged();
        }

    }

    /**
     * 轮播图销毁开启
     */

    @Override
    public void onStart() {
        super.onStart();

        viewPagerIndicator1.setVisible(true);
    }


    @Override
    public void onPause() {
        super.onPause();

        viewPagerIndicator1.setVisible(false);
    }

    //更新全部商品时间
    public void notifyTimeData(){
        String appDou = getString(R.string.app_mine_currencyname);
        if(currenttime>=0 && !isEnd) {
                     time =  auction_detail.getAuction().getTime();
                     start =  auction_detail.getAuction().getStart();
            //有start时间时
                       if(isstart)
                       {
//                           bidauction.setText(strStartTime + " 开始");
                           bidauction.setEnabled(false);
                           bidauction.setBackgroundResource(R.drawable.corner_gray_bg);
                           setCountDown(start);
                           if(start==0)
                           {
                               bidauction.setText("出价(1"+appDou+"或1赠豆一次)");
                               bidauction.setEnabled(true);
                               bidauction.setBackgroundResource(R.drawable.corner_red_bg_selector);
                               isstart = false;
                           }
                       }
                       //没有start时间时
                       else {
                           setCountDown(time);
                           if(isMost)
                           {
                               bidauction.setText("你已最高");
                               bidauction.setEnabled(false);
                               bidauction.setBackgroundResource(R.drawable.corner_gray_bg);
                           }
                           else
                           {
                               bidauction.setText("出价(1"+appDou+"或1赠豆一次)");
                               bidauction.setEnabled(true);
                               bidauction.setBackgroundResource(R.drawable.corner_red_bg_selector);
                           }
                            if (time == 0) {
                                if( bh_listdata!=null&& bh_listdata.size()>0)
                                {
                                    bh_listdata.get(0).setGetting("获得者");
                                    detail_grid_sort.updateUI();
                                }
                                bid_range_ll.setVisibility(View.VISIBLE);
                                bidauction.setText("出价结束,计算中....");
                                bidauction.setEnabled(false);
                                bidauction.setBackgroundResource(R.drawable.corner_gray_bg);
                                handler1.removeCallbacks(mRunnable1);
                            }
                        }
            }
        }

    private void setCountDown(int time) {
        int day = 1000 * 60 * 60 * 24;
        int hour = 1000 * 60 * 60;
        int min = 1000 * 60;
        int sec = 1000;
        double d1 = time * 1.0 / day;
        double d2 = time * 1.0 / hour;
        if (d2 > 1) {
            ll_cd1.setVisibility(View.GONE);
            ll_cd2.setVisibility(View.VISIBLE);
            int dayNum = time / day;
            int hourNum = time / hour % 24;
            int minuteNum = time / min % 60;
            int secondNum = time / sec % 60;
            if (d1 > 1) {
                cd_day.setText(dayNum + "天");
            } else {
                cd_day.setText("");
            }
            cd_hour.setText(hourNum + "时");
            cd_minute.setText(minuteNum + "分");
            cd_second.setText(secondNum + "秒");
        } else {
            ll_cd1.setVisibility(View.VISIBLE);
            ll_cd2.setVisibility(View.GONE);
            minute = String.format("%02d", time / 1000 / 60);
            second = String.format("%02d", time / 1000 % 60);
            millsecond = String.format("%02d", time % 1000 / 40 * 4);
            kill_millsecond.setText(millsecond);
            kill_minute.setText(minute);
            kill_second.setText(second);
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {

//            Intent intent = new Intent();
//            Bundle bundle = new Bundle();
//            bundle.putString("auction_id",auction_detail.getAuction().getId());
//            bundle.putString("auction_period",auction_detail.getAuction().getPeriod());
//            intent.putExtras(bundle);
//            setResult(RESULT_OK, intent);
            finish();
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (DETAIL_SHOW == 2) {
            service = null;
            mcontext.unregisterReceiver(mBroadcastReceiver);
            mBroadcastReceiver = null;
        } else {
            service = null;
            mcontext.unregisterReceiver(mBroadcastReceiver);
            mBroadcastReceiver = null;
            handler1.removeCallbacks(mRunnable1);
        }
    }
}
